/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Controller;

import DB_REDIS.Redis_Rd;
import DB_REDIS.Redis_W;
import Model.ModelItem;
import Model.ModelUser;
import Model.Request.ClientRequest;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import share.KeysDefinition;
import share.ShareMacros;

/**
 *
 * @author LinhTA
 */
public class ProfileController extends Controller{
    
     private static Logger logger_ = Logger.getLogger(ProfileController.class);
    
    @Override  
    public void handle(ClientRequest request, HttpServletResponse resp) 
    {
         try {
            prepareHeader(resp);
          
            switch(request._method)
            { 
                case "get":
                     getInfo(request, resp);
                    break;
                case "set":
                    updateInfo(request, resp);
                    break;
                case "useLife":
                    useLife(request, resp);
                   break;
                case "getLife":
                    getLife(request, resp);
                   break;
                case "addExp":
                    incrExp(request, resp);
                   break;
                default:
                   outFalse(resp);
            }
            
        } catch (Exception ex) {
            logger_.error("Profile.handle:" + ex.getMessage() + ", Username:" + request._uid.toString(), ex);
        }
    }
    
    @Override
    protected JSONObject defaultResponse_False()
    {
       JSONObject data = new JSONObject();
        data.put(share.ShareMacros.SUSSCES, "false");
        data.put(ShareMacros.GOLD, "0");
         data.put(ShareMacros.COIN, "0");
         data.put(ShareMacros.EXP, "0");
         data.put(ShareMacros.NAME, "");
          data.put(ShareMacros.EMAIL, "");
        data.put(ShareMacros.FACEID, "");
       data.put(ShareMacros.MEID,"");
       data.put(ShareMacros.TIME, String.valueOf(utilities.time.UtilTime.getTimeNow()));
       data.put(ShareMacros.EXP,"0");
       
        return  data;
    }
    
     public void updateInfo( ClientRequest req, HttpServletResponse resp )
    {
       
        String meID = req._meID;//ids.get(ShareMacros.MEID);
        String faceID = req._fbID;//ids.get(ShareMacros.FACEID);
        String uid = req._uid;//ids.get(ShareMacros.ID);
        String appId = req._appId;
        
        String name = req._data.get(ShareMacros.NAME);
        String email = req._data.get(ShareMacros.EMAIL);
                       
        Map<String,String> data = new HashMap<>();
        data.put(ShareMacros.NAME, name);
        data.put(ShareMacros.EMAIL, email);
        
        if(uid != "")
            setDefault(uid);
        
        String check = "false";
        if(meID != null && !meID.isEmpty() )
        {
            if (Redis_W.getInstance().hset(uid, data) != "-1" && Redis_W.getInstance().sadd(KeysDefinition.getAllUserME(appId),meID) != -1 )
                check = "true";
            else
                check = "false";
        }
        else
            if(faceID != null && !faceID.isEmpty() )
            {
                if (Redis_W.getInstance().hset(uid, data) != "-1" && Redis_W.getInstance().sadd(KeysDefinition.getAllUserFB(appId),faceID) != -1 && Redis_W.getInstance().set(email,uid )!= -1)
                    check = "true";
                else
                    check = "false";
            }
        
        JSONObject mapjson = new JSONObject();
       mapjson.put(ShareMacros.SUSSCES, check);
       out(mapjson.toJSONString(), resp);
       
      
       // addAppId(uid, appId);
    }
    
    public void getInfo( ClientRequest req, HttpServletResponse resp )
    {
        
       String meId = req._meID;//ids.get(ShareMacros.MEID);
        String faceId = req._fbID;//ids.get(ShareMacros.FACEID);
        String uid = req._uid;//ids.get(ShareMacros.ID);
       
        ModelUser modUser = new ModelUser(uid);
              
       JSONObject mapjson = new JSONObject();
       mapjson.putAll(modUser.getInfo(faceId, meId));
     
        out(mapjson.toJSONString(), resp);
    }
    
    public void setDefault(String uid)
     {
//         String keyCoin = KeysDefinition.getKeyCoinUser(uid);
//         String coin = "";
//         int retries = configuration.Configuration.retries;
//         while(retries>0)
//         {
//             coin = Redis_Rd.getInstance().get(keyCoin);
//             if(coin.isEmpty() || coin == null)
//                 retries --;
//             else break;
//         }
//               
//         if(coin.isEmpty() || coin == null)
//         {
//             retries = configuration.Configuration.retries;
//              while(retries>0)
//            {
//                long ret = Redis_W.getInstance().set(keyCoin,configuration.Configuration.Coin_UserDefault);
//                if(ret == -1)
//                    retries --;
//                else break;
//            }
//         }
//        
     }
    
    public void getLife(ClientRequest req, HttpServletResponse resp)
      {
          JSONObject mapjson = new JSONObject();
          mapjson.put(ShareMacros.TIME, String.valueOf(utilities.time.UtilTime.getTimeNow()));
             mapjson.putAll(ModelItem.getLifeVSTime(req._uid, resp));
             ModelItem.out(mapjson.toJSONString(), resp);
      }
    
    public void buyLife(ClientRequest req, HttpServletResponse resp)
    {
        ModelUser modUser = new ModelUser(req._uid);
        
         JSONObject mapjson = new JSONObject();
          mapjson.put(ShareMacros.TIME, String.valueOf(utilities.time.UtilTime.getTimeNow()));
         mapjson.putAll(modUser.buyLife());
         
         ModelItem.out(mapjson.toJSONString(), resp);
    }
    
    public void useLife(ClientRequest req, HttpServletResponse resp)
     {
         Map<String,String> data = new HashMap<String,String>();
         
         Map<String,String> timeVsLife = new HashMap<String,String>();
         timeVsLife = ModelItem.getLifeVSTime(req._uid, resp);
         
         int life = Integer.parseInt(timeVsLife.get(ShareMacros.LIFE));
         long timeOld = Long.parseLong(timeVsLife.get(ShareMacros.LASTTIME));
         
         if( life>= 1 )
         {
             long timeNow = utilities.time.UtilTime.getTimeNow();
             long timeAdd = Long.parseLong(libCore.Config.getParam(ShareMacros.COUNTDOWN, ShareMacros.LIFE));
             
              String ret ="";
              int lifeMax = Integer.parseInt(libCore.Config.getParam(ShareMacros.MAX, ShareMacros.LIFE));
             
              long time = timeOld;
             if(timeNow >= (timeAdd+timeOld) || life == lifeMax)
                time = timeNow;
              
              life = life -1;          
             
            
             
             data.put(ShareMacros.LIFE,String.valueOf(life));
             data.put(ShareMacros.LASTTIME, String.valueOf(time));
             
             ret = Redis_W.getInstance().hset(req._uid, data);
             
             if(ret == null )
             {
                 outFalse(resp);
                 return;
             }
             else
             {
                 data.put(ShareMacros.SUSSCES, "true");
                 data.putAll(data);             
             }
         }
         else
         {
             data.put(ShareMacros.SUSSCES, "false");
             data.put(ShareMacros.LIFE, String.valueOf(life));
             data.put(ShareMacros.LASTTIME, "-1");
         }
         
         data.put(ShareMacros.TIME, String.valueOf(utilities.time.UtilTime.getTimeNow()));
            JSONObject mapjson = new JSONObject();
       mapjson.putAll(data);
        ModelItem.out(mapjson.toJSONString(), resp);
     }
    
    public void incrExp(ClientRequest req, HttpServletResponse resp)
    {
        String uid = req._uid;
        long exp = Long.parseLong(req._data.get(ShareMacros.EXP));
        
        long newExp = 0;
        newExp = Redis_W.getInstance().hincrBy(uid, ShareMacros.EXP, exp);
        
        JSONObject mapjson = new JSONObject();
        mapjson.put(ShareMacros.EXP, newExp);
        
        out(mapjson.toJSONString(), resp);
        
    }
    
}
